#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import os
import time
from spider.requests_helper import Request
from lxml import html
import re
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium import webdriver


def open_url(url):
    # 访问网址
    driver.get(url)


def login(username, password):
    # 输入账号
    driver.find_element_by_id("txtUserName2").send_keys(username)
    # 输入密码
    driver.find_element_by_id("txtPassword2").send_keys(password)
    time.sleep(1)
    # 点击登录按钮
    driver.find_element_by_id("btnLogin2").click()


def spider_page_total():
    url = "http://edu.piesat.cn/kng/knowledgecatalogsearch.htm?t=VideoKnowledge&h=menu"
    driver.get(url)
    # 获得html内容
    html_text = driver.page_source

    # 获得xpath对象
    selector = html.fromstring(html_text)
    info = selector.xpath('//a[@class="pagenumber"][last()]/text()')
    return info[0]


def spider(page):
    """ 爬取http://edu.piesat.cn/的课程 """
    url = "http://edu.piesat.cn/kng/knowledgecatalogsearch.htm?t=VideoKnowledge&h=menu&pi={page}".format(page=page)
    # 最大化浏览器窗口
    # driver.maximize_window()
    # print ("正在访问{}".format(url))
    driver.get(url)
    # 获得html内容
    html_text = driver.page_source

    # 获得xpath对象
    selector = html.fromstring(html_text)

    info_list = selector.xpath('//img/@onclick')
    url_list = []
    for info in info_list:
        url = info.split("'")[1]
        url_list.append("http://edu.piesat.cn{url}".format(url=url))
    return url_list
    # driver.close()


def init_url_list():
    total = int(spider_page_total()) + 1
    read_file = open('E:/PyCharmFile/python_demo/spider/SoulBGM.md', 'r', encoding='utf-8')
    readlines = read_file.readlines()
    context = ''.join(readlines)
    file = open('E:/PyCharmFile/python_demo/spider/SoulBGM.md', 'a', encoding='utf-8')
    info_list = []
    for page in range(1, total):
        url_list = spider(page)
        for url in url_list:
            if context.count(url) == 0:
                video_play(url)
                time.sleep(2)
                # 获得html内容
                html_text = driver.page_source
                # 获得xpath对象
                selector = html.fromstring(html_text)
                time_str = str(selector.xpath('//div[@id="divHead2"]/span[@id="divStartArea"]/span[@id="spanLeavTimes"]/text()')[0])
                completion_rate = selector.xpath('//div[@id="divHead2"]/span[@id="ScheduleText"]/text()')[0]
                second = convert_second(time_str)
                courseware_info = {}
                courseware_info['url'] = url
                courseware_info['duration'] = second
                courseware_info['state'] = 'y' if completion_rate == '100%' else 'n'
                info_list.append(courseware_info)

    info_list.sort(key=lambda info: info['duration'], reverse=False)
    info_list.sort(key=lambda info: info['state'], reverse=True)
    for info in info_list:
        now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        file.write('| {url} | {state} | {duration} | {time} |\n'.format(url=info['url'], state=info['state'],
                                                                        time=now if info['state'] == 'y' else '',
                                                                        duration=info['duration']))


def convert_second(time_str):
    strptime = time.time()
    if time_str.count("小时") == 0 and time_str.count("分钟") == 0 and time_str.count("秒") == 0:
        return 0

    if time_str.count("小时") > 0 and time_str.count("分钟") > 0 and time_str.count("秒") > 0:
        strptime = time.strptime(time_str, '%H小时%M分钟%S秒')
    elif time_str.count("小时") > 0 and time_str.count("分钟") > 0:
        strptime = time.strptime(time_str, '%H小时%M分钟')
    elif time_str.count("小时") > 0 and time_str.count("秒"):
        strptime = time.strptime(time_str, '%H小时%S秒')
    elif time_str.count("小时") > 0:
        strptime = time.strptime(time_str, '%H小时')
    elif time_str.count("分钟") > 0 and time_str.count("秒") > 0:
        strptime = time.strptime(time_str, '%M分钟%S秒')
    elif time_str.count("分钟") > 0:
        strptime = time.strptime(time_str, '%M分钟')
    elif time_str.count("秒") > 0:
        strptime = time.strptime(time_str, '%S秒')

    hour = strptime.tm_hour
    minute = strptime.tm_min
    second = strptime.tm_sec

    return (hour * 60 * 60) + (minute * 60) + second


def video_play(url):
    try:
        driver.get(url)
        time.sleep(2)
        # 点击视频界面
        video = driver.find_element_by_id("vjs_video_3_html5_api")
        video_url = driver.execute_script("return arguments[0].currentSrc;", video)
        video.get_property("width")
        video.click()
        driver.execute_script("return arguments[0].play()", video)
    except BaseException:
        print("重试")
        video_play(url)


def watch():
    global state, watch_count
    if completion_rate == "100%":
        state = 'y'
        now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        read_lines[index] = '| {url} | {state} | 0 | {time} |\n'.format(url=url, state=state, time=now)
    else:
        time_str = str(selector.xpath(
            '//div[@id="divHead2"]/span[@id="divStartArea"]/span[@id="spanLeavTimes"]/text()')[0])
        print("需要观看", time_str)
        second = convert_second(time_str)
        # if second > 20 * 60:
        #     return
        sleep_second = 2 * 60
        surplus = second % (sleep_second)
        circulate_count = second / (sleep_second)
        circulate_count = circulate_count if surplus == 0 else circulate_count + 1
        circulate_count = int(circulate_count)
        for i in range(0, circulate_count):
            if circulate_count == circulate_count - 1 and surplus != 0:
                time.sleep(surplus)
            else:
                time.sleep(sleep_second)
            video = driver.find_element_by_id("vjs_video_3_html5_api")
            driver.execute_script("return arguments[0].pause()", video)
            time.sleep(2)
            driver.execute_script("return arguments[0].play()", video)
        state = 'y'
        now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        read_lines[index] = '| {url} | {state} | 0 | {time} | 0 |\n'.format(url=url, state=state, time=now)
        watch_count = watch_count + 1


if __name__ == '__main__':
    # chrome_driver = "D:/CareerSoftware/chromedriver/chromedriver.exe"
    # driver = webdriver.Chrome(executable_path=chrome_driver)
    d = DesiredCapabilities.CHROME
    d['loggingPrefs'] = {'performance': 'ALL'}
    # 设置谷歌浏览器参数，设置语言和浏览器版本（使用真实浏览器头信息代替字符浏览器头）
    options = webdriver.ChromeOptions()
    # options.add_argument('lang=zh_CN.UTF-8')
    # 设置静音
    options.add_argument('--mute-audio')
    driver = webdriver.Chrome(chrome_options=options)
    login_url = "http://edu.piesat.cn/login.htm"
    username = "heruijie"
    password = "jie1006454752"
    open_url(login_url)
    login(username, password)
    time.sleep(2)
    # init_url_list()
    read_file = open('E:/PyCharmFile/python_demo/spider/SoulBGM.md', 'r', encoding='utf-8')
    read_lines = read_file.readlines()
    lines = [str(line) for line in read_lines]
    index = 0
    watch_count = 0
    watch_total = 20
    for line in lines:
        if watch_count >= watch_total:
            break
        split = line.split("|")
        url = str(split[1]).strip()
        state = str(split[2]).strip()
        if url.count("http") > 0:
            if state == 'n':
                video_play(url)
                time.sleep(2)
                # 获得html内容
                html_text = driver.page_source
                # 获得xpath对象
                selector = html.fromstring(html_text)
                completion_rate = selector.xpath('//div[@id="divHead2"]/span[@id="ScheduleText"]/text()')[0]
                watch()
        index = index + 1
        print(index)
    f = open('E:/PyCharmFile/python_demo/spider/SoulBGM.md', 'w+', encoding='utf-8')
    f.writelines(read_lines)
    print("完成今日课件观看")
